package com.leyou.auth.intercepter;

import com.leyou.auth.constans.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.local.UserContext;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登录拦截器
 */
public class LogInInterceptor implements HandlerInterceptor {

    private JwtUtils jwtUtils;

    public LogInInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    //在此进行登录拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.通过request获取cookie然后获取jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        if (StringUtils.isBlank(jwt)) {
            throw new LyException(401, "未登录");
        }
        //2.获取用户信息,并验证
        Payload payload = jwtUtils.parseJwt(jwt);
        if(payload == null){
            throw new LyException(401, "未登录");
        }
        UserDetails user = payload.getUserDetail();
        if (user == null) {
            throw new LyException(401, "未登录");
        }
        //存储数据
        UserContext.setUser(user);
        UserContext.setJwt(jwt);
        //3.放行
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
